﻿using HomagChina.CCT.DataTypeModel;
using HomagChina.CCT.Router;
using HomagChina.CCT.Views;
using HomagGroup.Base.UI;
using HomagGroup.Base.UI.Controls;
using HomagGroup.Base.UI.Themes.Resources;
using HomagGroup.Base.UI.Windows;
using HomagGroup.BaseUI.Properties;
using OfficeOpenXml;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using static HomagChina.CCT.ProcessResourceInternal;
using static HomagChina.CCT.Utility;
using Label = System.Windows.Controls.Label;

namespace HomagChina.CCT.ViewModels
{
    public class IntelligencePlatformViewModel : NotifyPropertyChangedBase
    {
        public ObservableCollection<Border> DeviceCurrentOptions { get; set; } = new ObservableCollection<Border>();
        private readonly ResourceDictionary _deviceTypeConfig;
        public RelayCommand EditCommand { get; }

        public RelayCommand SaveDevicePropertiesCommand { get; }
        public RelayCommand CancelDevicePropertiesCommand { get; }

        private Canvas _warehouse = new Canvas();

        public Canvas Warehouse
        {
            get => _warehouse;
            set { _warehouse = value; OnPropertyChanged(); }
        }

        private List<MachineInfoDataModel> machineInfoList = new List<MachineInfoDataModel>();

        public List<MachineInfoDataModel> MachineInfoList
        {
            get => machineInfoList;

            set
            {
                machineInfoList = value;
                OnPropertyChanged();
            }
        }

        private Rectangle _selectedRectangle;

        public Rectangle SelectedRectangle
        {
            get => _selectedRectangle;
            set { _selectedRectangle = value; OnPropertyChanged(); }
        }

        private MachineInfoDataModel _SelectedMachineInfo = new MachineInfoDataModel();

        public MachineInfoDataModel SelectedMachineInfo
        {
            get => _SelectedMachineInfo;
            set { _SelectedMachineInfo = value; OnPropertyChanged(); }
        }

        private string _Title = "Device Model List";

        public string Title
        {
            get => _Title;
            set { _Title = value; OnPropertyChanged(); }
        }

        private int _MinHeight = 830;

        public int MinHeight
        {
            get => _MinHeight;
            set { _MinHeight = value; OnPropertyChanged(); }
        }

        private bool _isDragging;
        private Point _startPoint;

        public IntelligencePlatformViewModel()
        {
            UIAdjustments.CurrentThreadLanguageManager.CultureChanged += NavigateServices.Instance.LanguageManagerCultureChanged;
            CreateMachineList();
            _deviceTypeConfig = new ResourceDictionary
            {
                Source = new Uri("pack://application:,,,/HomagGroup.BaseUI;component/Config/DeviceTypeConfig.xaml")
            };
            Warehouse.Background = Brushes.Transparent;
            Warehouse.MouseLeftButtonDown += Warehouse_MouseLeftButtonDown;
            EditCommand = new RelayCommand(EditMachinInfo);
            CancelDevicePropertiesCommand = new RelayCommand(HandleCancelDeviceProperties);
            SaveDevicePropertiesCommand = new RelayCommand(HandleSaveDeviceProperties);
        }

        private void HandleSaveDeviceProperties()
        {
            CreateMachineList();
            HomagGroup.Base.UI.Windows.MessageBox.Show("Save Successful!");
        }

        private void HandleCancelDeviceProperties()
        {
            CreateMachineList();
        }

        private void EditMachinInfo()
        {
            if (SelectedRectangle != null)
            {
                SelectedRectangle.Uid = SelectedMachineInfo.MachineCode;
                SelectedRectangle.Width = SelectedMachineInfo.MachineWidth;
                SelectedRectangle.Height = SelectedMachineInfo.MachineHeight;
                SelectedRectangle.Fill = BitMapConvertsImageBrush(SelectedMachineInfo.MachineImagePath);
                SelectedRectangle.Opacity = SelectedMachineInfo.MachineImageOpactity;
            }
        }

        public void HandleClear()
        {
            MachineInfoList.Clear();
            SelectedRectangle = null;
            SelectedMachineInfo = null;
            Warehouse.Children.Clear();
        }

        private void CreateMachineList()
        {
            DeviceCurrentOptions.Clear();
            Title = "Device Model List";
            MinHeight = 830;
            foreach (DictionaryEntry item in ImageResource.ResourceManager.GetResourceSet(System.Globalization.CultureInfo.CurrentCulture, true, true))
            {
                string MachineImagePath = item.Key.ToString();
                Border border = new Border
                {
                    BorderBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#c2c2c2")),
                    BorderThickness = new Thickness(1),
                    CornerRadius = new CornerRadius(10, 10, 0, 0),
                    Margin = new Thickness(5)
                };

                // 创建StackPanel
                StackPanel stackPanel = new StackPanel
                {
                    Orientation = Orientation.Vertical,
                    VerticalAlignment = VerticalAlignment.Center,
                    HorizontalAlignment = HorizontalAlignment.Center,
                    Width = 150
                };

                // 创建Rectangle
                Rectangle rectangle = new Rectangle
                {
                    Uid = MachineImagePath,
                    Margin = new Thickness(5),
                    Width = 150,
                    Height = 70,
                    Fill = BitMapConvertsImageBrush(MachineImagePath) // 使用你的方法设置Fill
                };

                // 创建Label
                Label label = new Label
                {
                    FontSize = 14,
                    Width = 150,
                    HorizontalContentAlignment = HorizontalAlignment.Center,
                    Content = MachineImagePath,
                    Background = GetHexadecimalColor("#DCDCDC"),
                    HorizontalAlignment = HorizontalAlignment.Center
                };

                // 将Rectangle和Label添加到StackPanel
                stackPanel.Children.Add(rectangle);
                stackPanel.Children.Add(label);

                stackPanel.MouseLeftButtonUp += HandleAddMachine;

                // 将StackPanel添加到Border
                border.Child = stackPanel;

                // 将Border添加到集合
                DeviceCurrentOptions.Add(border);
            }
        }

        private string GetDeviceTypeByMachineName(string machineName)
        {
            return _deviceTypeConfig.Contains(machineName) ? _deviceTypeConfig[machineName].ToString() : "Unknown";
        }

        private void HandleAddMachine(object sender, MouseButtonEventArgs e)
        {
            if (sender is StackPanel stackPanel)
            {
                var label = stackPanel.Children.OfType<Label>().FirstOrDefault();
                string machineName = label.Content.ToString();
                string machineId = new Random().Next(1, 1000).ToString();
                string deviceType = GetDeviceTypeByMachineName(machineName);
                MachineInfoDataModel MachineInfo = new MachineInfoDataModel
                {
                    MachineCode = machineId,
                    MachineHeight = 80,
                    MachineWidth = 200,
                    Xposition = 0,
                    Yposition = 0,
                    DeviceType = deviceType,
                    MachineImagePath = label.Content.ToString(),
                    MachineImageOpactity = 1,
                    CreationDate = DateTime.Now,
                    ModificationDate = DateTime.Now
                };

                Rectangle ImageRectangle = new Rectangle
                {
                    Uid = machineId,
                    Width = MachineInfo.MachineWidth,
                    Height = MachineInfo.MachineHeight,
                    Fill = BitMapConvertsImageBrush(label.Content.ToString()),
                    Opacity = MachineInfo.MachineImageOpactity,
                    Focusable = true
                };
                ImageRectangle.MouseLeftButtonDown += HandleSelectionDevice;
                ImageRectangle.MouseMove += HandleMoveSelectedDevice;
                ImageRectangle.MouseLeftButtonUp += MachineMouseLeftButtonUp;
                ImageRectangle.MouseRightButtonDown += HandleEditDeviceProperties;
                ImageRectangle.KeyDown += HandleDeleteDevice;
                MachineInfoList.Add(MachineInfo);
                Canvas.SetLeft(ImageRectangle, MachineInfo.Xposition);
                Canvas.SetTop(ImageRectangle, MachineInfo.Yposition);
                Warehouse.Children.Add(ImageRectangle);
                Warehouse.InvalidateVisual();
            }
        }

        private void HandleDeleteDevice(object sender, KeyEventArgs e)
        {
            if ((e.Key == Key.Delete || e.Key == Key.Back) && SelectedRectangle != null)
            {
                Warehouse.Children.Remove(SelectedRectangle);
                MachineInfoList.Remove(SelectedMachineInfo);
                DeselectRectangle();
            }
        }

        private void HandleEditDeviceProperties(object sender, MouseButtonEventArgs e)
        {
            if (sender is Rectangle rectangle)
            {
                DeselectRectangle();
                SelectedRectangle = rectangle;
                SelectedMachineInfo = MachineInfoList.Find(s => s.MachineCode == rectangle.Uid);
                Title = "Device Model Properties";
                MinHeight = 760;
                DeviceCurrentOptions.Clear();
                if (SelectedMachineInfo.DeviceType == "Cross")
                {
                    CreateFormItems(nameof(SelectedMachineInfo.Reference), "Reference", ControlType.InputField);
                    CreateFormItems(nameof(SelectedMachineInfo.DeviceType), "DeviceType", ControlType.DropDownList, icon: Icon.Tune, dropDownItems: new List<string> { "滚筒1", "滚筒2" });
                    CreateFormItems(nameof(SelectedMachineInfo.InfeedSensor), "Infeed Sensor", ControlType.ToggleSwitch, extraInfo: "inFeed");
                    CreateFormItems(nameof(SelectedMachineInfo.CreepSensor), "Creep Sensor", ControlType.ToggleSwitch, icon: Icon.PlayPause);
                    CreateFormItems(nameof(SelectedMachineInfo.StopSensor), "Stop Sensor", ControlType.ToggleSwitch, icon: Icon.Stop);
                    CreateFormItems(nameof(SelectedMachineInfo.LSideObstruction), "L-side obstruction", ControlType.ToggleSwitch, icon: Icon.RotateLeft);
                    CreateFormItems(nameof(SelectedMachineInfo.SSideObstruction), "S-side obstruction", ControlType.ToggleSwitch, icon: Icon.RotateRight);
                    CreateFormItems(nameof(SelectedMachineInfo.Length), "Length", ControlType.InputField, FieldType.Float, 140, "mm");
                    CreateFormItems(nameof(SelectedMachineInfo.Width), "Width", ControlType.InputField, FieldType.Float, 140, "mm");
                    CreateFormItems(nameof(SelectedMachineInfo.Height), "Height", ControlType.InputField, FieldType.Float, 140, "mm");
                    CreateFormItems(nameof(SelectedMachineInfo.Gap), "Gap", ControlType.InputField, FieldType.Integer, 140, "mm");
                    CreateFormItems(nameof(SelectedMachineInfo.RollerQuantity), "Roller Quantity", ControlType.InputField, FieldType.Float, 140, "pcs");
                    CreateFormItems(nameof(SelectedMachineInfo.Belt), "Belt", ControlType.InputField, FieldType.Float, 140, "pcs");
                }
                else if (SelectedMachineInfo.DeviceType == "Conveyor")
                {
                    CreateFormItems(nameof(SelectedMachineInfo.Reference), "Reference", ControlType.InputField);
                    CreateFormItems(nameof(SelectedMachineInfo.DeviceType), "DeviceType", ControlType.DropDownList, icon: Icon.Tune, dropDownItems: new List<string> { "滚筒1", "滚筒2" });
                    CreateFormItems(nameof(SelectedMachineInfo.InfeedSensor), "Infeed Sensor", ControlType.ToggleSwitch, extraInfo: "inFeed");
                    CreateFormItems(nameof(SelectedMachineInfo.CreepSensor), "Creep Sensor", ControlType.ToggleSwitch, icon: Icon.PlayPause);
                    CreateFormItems(nameof(SelectedMachineInfo.StopSensor), "Stop Sensor", ControlType.ToggleSwitch, icon: Icon.Stop);
                    CreateFormItems(nameof(SelectedMachineInfo.Length), "Length", ControlType.InputField, FieldType.Float, 140, "mm");
                    CreateFormItems(nameof(SelectedMachineInfo.Width), "Width", ControlType.InputField, FieldType.Float, 140, "mm");
                    CreateFormItems(nameof(SelectedMachineInfo.Height), "Height", ControlType.InputField, FieldType.Float, 140, "mm");
                    CreateFormItems(nameof(SelectedMachineInfo.Gap), "Gap", ControlType.InputField, FieldType.Integer, 140, "mm");
                    CreateFormItems(nameof(SelectedMachineInfo.RollerQuantity), "Roller Quantity", ControlType.InputField, FieldType.Float, 140, "pcs");
                }
                else
                {
                    CreateFormItems(nameof(SelectedMachineInfo.Reference), "Reference", ControlType.InputField);
                    CreateFormItems(nameof(SelectedMachineInfo.DeviceType), "DeviceType", ControlType.DropDownList, icon: Icon.Tune, dropDownItems: new List<string> { "滚筒1", "滚筒2" });
                    CreateFormItems(nameof(SelectedMachineInfo.InfeedSensor), "Infeed Sensor", ControlType.ToggleSwitch, extraInfo: "inFeed");
                    CreateFormItems(nameof(SelectedMachineInfo.CreepSensor), "Creep Sensor", ControlType.ToggleSwitch, icon: Icon.PlayPause);
                    CreateFormItems(nameof(SelectedMachineInfo.StopSensor), "Stop Sensor", ControlType.ToggleSwitch, icon: Icon.Stop);
                    CreateFormItems(nameof(SelectedMachineInfo.Length), "Length", ControlType.InputField, FieldType.Float, 140, "mm");
                    CreateFormItems(nameof(SelectedMachineInfo.Width), "Width", ControlType.InputField, FieldType.Float, 140, "mm");
                    CreateFormItems(nameof(SelectedMachineInfo.Height), "Height", ControlType.InputField, FieldType.Float, 140, "mm");
                    CreateFormItems(nameof(SelectedMachineInfo.Belt), "Belt", ControlType.InputField, FieldType.Float, 140, "pcs");
                }
            }
        }

        private void CreateFormItems(string propertyName, string label, ControlType controlType, FieldType fieldType = FieldType.Custom, int width = 290, string unit = null, IEnumerable<string> dropDownItems = null, string extraInfo = null, Icon icon = Icon.None)
        {
            Binding binding = new Binding(propertyName)
            {
                Source = SelectedMachineInfo,
                Mode = BindingMode.TwoWay,
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            };
            FrameworkElement control;
            switch (controlType)
            {
                case ControlType.InputField:
                    InputField inputField = new InputField
                    {
                        Label = GetLocaText(label),
                        IsImageVisible = false,
                        Width = width,
                        Unit = unit,
                        FieldType = fieldType
                    };
                    inputField.SetBinding(InputField.TextProperty, binding);
                    control = inputField;
                    break;

                case ControlType.DropDownList:
                    DropDownList dropDownList = new DropDownList
                    {
                        Width = width,
                        ItemsSource = dropDownItems,
                        Image = GetIconBrush(icon),
                        IsLabelVisible = false,
                        SelectedIndex = 0
                    };

                    dropDownList.SetBinding(DropDownList.SelectedItemProperty, binding);

                    control = dropDownList;
                    break;

                case ControlType.ToggleSwitch:
                    ToggleSwitch toggleSwitch = new ToggleSwitch
                    {
                        Width = width,
                        Label = GetLocaText(label),
                        Image = extraInfo == null ? GetIconBrush(icon) : GetResourceBrush(extraInfo)
                    };
                    toggleSwitch.SetBinding(ToggleSwitch.IsCheckedProperty, binding);
                    control = toggleSwitch;
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(controlType), controlType, null);
            }

            Border border = new Border
            {
                Margin = new Thickness(2),
                Child = control
            };

            DeviceCurrentOptions.Add(border);
        }

        private void HandleSelectionDevice(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
            if (sender is Rectangle rectangle)
            {
                DeselectRectangle();
                SelectedRectangle = rectangle;
                SelectedMachineInfo = MachineInfoList.Find(s => s.MachineCode == rectangle.Uid);
                SelectedRectangle.Stroke = new SolidColorBrush(Colors.DarkBlue);
                SelectedRectangle.StrokeThickness = 2;
                SelectedRectangle.StrokeDashArray = new DoubleCollection() { 2, 2 };
                SelectedRectangle.StrokeDashCap = PenLineCap.Round;
                SelectedRectangle.Focus();
                _isDragging = true;
                _startPoint = e.GetPosition(Warehouse);
                SelectedRectangle.CaptureMouse();
            }
        }

        private void HandleMoveSelectedDevice(object sender, MouseEventArgs e)
        {
            if (_isDragging && SelectedRectangle != null)
            {
                Point currentPoint = e.GetPosition(Warehouse);
                double offsetX = currentPoint.X - _startPoint.X;
                double offsetY = currentPoint.Y - _startPoint.Y;

                double newLeft = Canvas.GetLeft(SelectedRectangle) + offsetX;
                double newTop = Canvas.GetTop(SelectedRectangle) + offsetY;

                Canvas.SetLeft(SelectedRectangle, newLeft);
                Canvas.SetTop(SelectedRectangle, newTop);
                _startPoint = currentPoint;
            }
        }

        private void MachineMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (_isDragging)
            {
                _isDragging = false;
                if (SelectedRectangle != null)
                {
                    SelectedRectangle.ReleaseMouseCapture();
                    Point currentPoint = e.GetPosition(Warehouse);
                    double offsetX = currentPoint.X - _startPoint.X;
                    double offsetY = currentPoint.Y - _startPoint.Y;
                    double newLeft = Canvas.GetLeft(SelectedRectangle) + offsetX;
                    double newTop = Canvas.GetTop(SelectedRectangle) + offsetY;
                    SelectedMachineInfo.Xposition = newLeft;
                    SelectedMachineInfo.Yposition = newTop;
                }
            }
        }

        private void Warehouse_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.OriginalSource is Canvas)
            {
                DeselectRectangle();
                HandleCancelDeviceProperties();
            }
        }

        private void DeselectRectangle()
        {
            if (SelectedRectangle != null)
            {
                // 取消选中样式
                SelectedRectangle.Stroke = null;
                SelectedRectangle.StrokeThickness = 0;
                SelectedRectangle.StrokeDashArray = null;

                // 清空选中项
                SelectedRectangle = null;
                SelectedMachineInfo = null;
            }
        }

        public void ExportExcelFile()
        {
            if (MachineInfoList.Count() == 0)
            {
                HomagGroup.Base.UI.Windows.MessageBox.Show("There is no current device information!");
            }
            else
            {
                var result = HomagGroup.Base.UI.Windows.MessageBox.Show(
                         Application.Current.MainWindow,
                         GetLocaText("Please select the type of file you want to export!"),
                         GetLocaText("Prompt message"),
                         GetLocaText("Export PLC Interface"),
                         GetLocaText("Export Quotations"),
                         MessageBoxImage.Question,
                         MessageBoxResult.Yes);
                if (result == MessageBoxResult.Yes)
                {
                    ExportPLCInterface();
                }
                else if (result == MessageBoxResult.No)
                {
                    ExportQuotations();
                }
            }
        }

        public void ExportPLCInterface()
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            var openFileDialog = new Microsoft.Win32.OpenFileDialog
            {
                Filter = "Excel Files|*.xlsx",
                Title = "选择Excel模板文件"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                string templatePath = openFileDialog.FileName;
                FileInfo templateFile = new FileInfo(templatePath);

                var saveFileDialog = new Microsoft.Win32.SaveFileDialog
                {
                    Filter = "Excel Files|*.xlsx",
                    Title = "保存Excel文件"
                };

                if (saveFileDialog.ShowDialog() == true)
                {
                    string savePath = saveFileDialog.FileName;

                    using (var package = new ExcelPackage(templateFile))
                    {
                        var worksheet = package.Workbook.Worksheets[0];

                        int startRow = 2;

                        for (int i = 0; i < MachineInfoList.Count; i++)
                        {
                            var machineInfo = MachineInfoList[i];

                            // 设置默认样式
                            var defaultStyle = worksheet.Cells[startRow, 1, startRow + 3, 7].Style;
                            defaultStyle.Font.Size = 16;
                            defaultStyle.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                            defaultStyle.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                            defaultStyle.WrapText = true;

                            worksheet.Cells[startRow, 1, startRow, 7].Merge = true;
                            worksheet.Cells[startRow, 1].Value = machineInfo.Reference;
                            worksheet.Cells[startRow, 1].Style.Font.Size = 16;
                            worksheet.Cells[startRow, 1].Style.Font.Bold = true;
                            worksheet.Cells[startRow, 1].Style.Font.Italic = true;
                            worksheet.Cells[startRow, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                            worksheet.Cells[startRow, 1].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; // 设置Patte
                            worksheet.Cells[startRow, 1].Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#8497b0")); // 设置背景色

                            worksheet.Cells[startRow + 1, 1].Value = machineInfo.Reference;
                            worksheet.Cells[startRow + 1, 2].Value = "OrderState";
                            worksheet.Cells[startRow + 1, 3].Value = "Int";
                            worksheet.Cells[startRow + 1, 4].Value = "PC/PLC：R/W";
                            worksheet.Cells[startRow + 1, 5].Value = "订单状态(下同)";
                            worksheet.Cells[startRow + 1, 6].Value = "99:已取消当前订单 10:Plc请求任务 20:CC下发任务 30:Plc完成任务 40:CC完成任务 (下同)";
                            worksheet.Cells[startRow + 1, 7].Value = "初始值为1000，每次交互完成PLC需将值修改为初始值(下同)";

                            worksheet.Cells[startRow + 2, 1].Value = machineInfo.Reference;
                            worksheet.Cells[startRow + 2, 2].Value = "Reference";
                            worksheet.Cells[startRow + 2, 3].Value = "string";
                            worksheet.Cells[startRow + 2, 4].Value = "PLc:R PC:W";
                            worksheet.Cells[startRow + 2, 5].Value = "";
                            worksheet.Cells[startRow + 2, 6].Value = "";
                            worksheet.Cells[startRow + 2, 7].Value = "";

                            worksheet.Cells[startRow + 3, 1].Value = machineInfo.Reference;
                            worksheet.Cells[startRow + 3, 2].Value = "Direction";
                            worksheet.Cells[startRow + 3, 3].Value = "int";
                            worksheet.Cells[startRow + 3, 4].Value = "Pc:W    Plc:R";
                            worksheet.Cells[startRow + 3, 5].Value = "";
                            worksheet.Cells[startRow + 3, 6].Value = "";
                            worksheet.Cells[startRow + 3, 7].Value = "";

                            startRow += 4;
                        }
                        // 设置最后两条数据的样式
                        var finalStyle = worksheet.Cells[startRow, 1, startRow + 2, 7].Style;
                        finalStyle.Font.Size = 16;
                        finalStyle.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        finalStyle.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Center;
                        finalStyle.WrapText = true;
                        worksheet.Cells[startRow, 1, startRow, 7].Merge = true;
                        worksheet.Cells[startRow, 1].Value = "System_";
                        worksheet.Cells[startRow, 1].Style.Font.Size = 16;
                        worksheet.Cells[startRow, 1].Style.Font.Bold = true;
                        worksheet.Cells[startRow, 1].Style.Font.Italic = true; // 设置斜体
                        worksheet.Cells[startRow, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                        worksheet.Cells[startRow, 1].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; // 设置Patte
                        worksheet.Cells[startRow, 1].Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#8497b0")); // 设置背景色

                        worksheet.Cells[startRow + 1, 1].Value = "System_";
                        worksheet.Cells[startRow + 1, 2].Value = "OperationMode";
                        worksheet.Cells[startRow + 1, 3].Value = "String";
                        worksheet.Cells[startRow + 1, 4].Value = "";
                        worksheet.Cells[startRow + 1, 5].Value = "系统的运行模式";
                        worksheet.Cells[startRow + 1, 6].Value = "\"Auto\"(一码一板)/\"Project\"(一码多板)";
                        worksheet.Cells[startRow + 1, 7].Value = "";

                        worksheet.Cells[startRow + 2, 1].Value = "System_";
                        worksheet.Cells[startRow + 2, 2].Value = "InfeedButton";
                        worksheet.Cells[startRow + 2, 3].Value = "BooL_";
                        worksheet.Cells[startRow + 2, 4].Value = "";
                        worksheet.Cells[startRow + 2, 5].Value = "上料按钮";
                        worksheet.Cells[startRow + 2, 6].Value = "在Project模式下,板件上线的同时点击了进料按钮Plc将该值赋值为True,代表工程单有板进料,CCT收到信号后处理数据,完成后将该值赋值为FaL_se,代表处理完成可进行下一次上料";
                        worksheet.Cells[startRow + 2, 7].Value = "";

                        package.SaveAs(new FileInfo(savePath));
                        HomagGroup.Base.UI.Windows.MessageBox.Show("文件已保存: " + savePath);
                    }
                }
            }
        }

        public void ExportToCSV(string ProjectName, string ProjectDescription)
        {
            if (ProjectName == null || ProjectName=="")
            {
                HomagGroup.Base.UI.Windows.MessageBox.Show("Please enter the project name!");
                return;
            }
            HandleCloseDialog();
            var saveFileDialog = new Microsoft.Win32.SaveFileDialog
            {
                Filter = "CSV Files|*.csv",
                Title = "保存CSV文件"
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                string savePath = saveFileDialog.FileName;

                using (StreamWriter writer = new StreamWriter(savePath))
                {
                    // 写入CSV文件的头部信息
                    writer.WriteLine("REFERENCE,DEVICETYPE,GAP,BELT,WIDTH,HEIGHT,LENGTH,ROLLERQUANTITY,INFEEDSENSOR,CREEPSENSOR,STOPSENSOR,LSIDEOBSTRUCTION,SSIDEOBSTRUCTION,MACHINEHEIGHT,MACHINEWIDTH,MACHINEPOSTION,XPOSITION,YPOSITION,MACHINEIMAGEOPACTITY,MACHINEIMAGEPATH,PROJECTNAME");

                    // 写入CSV文件的主体内容
                    for (int i = 0; i < MachineInfoList.Count; i++)
                    {
                        var machineInfo = MachineInfoList[i];
                        writer.WriteLine($"{machineInfo.Reference},{machineInfo.DeviceType},{machineInfo.Gap},{machineInfo.Belt},{machineInfo.Width},{machineInfo.Height},{machineInfo.Length},{machineInfo.RollerQuantity},{machineInfo.InfeedSensor},{machineInfo.CreepSensor},{machineInfo.StopSensor},{machineInfo.LSideObstruction},{machineInfo.SSideObstruction},{machineInfo.MachineHeight},{machineInfo.MachineWidth},{machineInfo.MachineCode},{machineInfo.Xposition},{machineInfo.Yposition},{machineInfo.MachineImageOpactity},{machineInfo.MachineImagePath},{ProjectName}");
                    }

                    HomagGroup.Base.UI.Windows.MessageBox.Show("文件已保存: " + savePath);
                }
            }
        }

        public void ExportQuotations()
        {
            HomagGroup.Base.UI.Windows.MessageBox.Show("Export Quotations");
        }

        public void HandleSaveProject()
        {
            SaveProjectDialogViewModel viewModel = new SaveProjectDialogViewModel();
            var a = UIAdjustments.CurrentThreadDialogManager.ShowDialog<SaveProjectDialog>(viewModel, null);
        }

        public void HandleCloseDialog()
        {
            CloseDiaLog(GetLocaText("SaveProject"));
        }
    }
}

public enum ControlType
{
    InputField,
    DropDownList,
    ToggleSwitch
}